package cn.wxxyhw.Dao;

import cn.wxxyhw.Entity.Message;
import cn.wxxyhw.Util.DataSourceUtil;
import cn.wxxyhw.Util.UnReadMessage;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 消息操作
 * @Author: 洪稳
 * @Date: 2019/6/3
 */
@Repository
public class MessageDao {
    static QueryRunner queryRunner ;
    static {
        queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    }
    /**
     * 保存消息
     * @param msg 消息实体类
     */
    public void save(Message msg) {
        String sql = "insert into message(`read`,fromId,toId,date,content) values(?,?,?,?,?)";
        try {
            queryRunner.update(sql,msg.getRead(),msg.getFromId(),msg.getToId(),msg.getDate(),msg.getContent());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询用户未读的消息
     * @param id 用户id
     * @return
     */
    public List<UnReadMessage> getNoReadMessages(String id) {
        List<UnReadMessage> query = null;
        String sql = "select fromId as username, count(*) as number from message where toId= ? and `read`= 0 group by fromId;";
        try {
            query = queryRunner.query(sql, new BeanListHandler<>(UnReadMessage.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 查询具体消息
     * @param friendId
     * @param uid
     * @return
     */
    public List<Message> getNoReadMessageDetail(String friendId, String uid) {
        List<Message> messages = null;
        String sql = "select * from message where fromId = ? and toId = ? and  `read`= 0";
        String updateSql = "update message set `read`=1 where fromId = ? and toId = ? and `read` = 0";
        try {
            messages = queryRunner.query(sql,new BeanListHandler<>(Message.class),friendId,uid);
            queryRunner.update(updateSql,friendId,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return messages;
    }

    /**
     * 查询消息记录
     * @param uid
     * @param myid
     * @return
     */
    public List<Message> getMessage(String uid, String myid) {
        List<Message> messages = null;
        String sql = "select * from message where fromId = ? and toId = ? or fromId = ? and toId = ?";
        try {
            messages = queryRunner.query(sql,new BeanListHandler<>(Message.class),uid,myid,myid,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return messages;
    }
}
